package com.songlin.bakejianshen;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;


import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.songlin.adapter.PersonAdapter;
import com.songlin.model.Person;
import com.songlin.model.State;
import com.songlin.utils.BitmapUtils;
import com.songlin.utils.DBUtils;
import com.songlin.utils.InfoUtils;
import com.songlin.utils.StringOrDate;

import java.io.ByteArrayOutputStream;
import java.sql.Blob;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by moqikaka on 17/5/26.
 */

public class LoadingActivity extends Activity {

    private String APP_ID = "35c8b2587ae1e794a40aa87d06c4ff6a";
    private ProgressDialog pd;

    private int mNum = 0;
    private int mNumSize = 0;

    List<com.songlin.db.Person> mPersons = new ArrayList<com.songlin.db.Person>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_loading);

        //获取
        //集成Bomb后台工具
        Bmob.initialize(this, APP_ID);
        Bmob.initialize(this, APP_ID, "bmob");

        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setTitle("提示");
        pd.setMessage("更新数据。。。");
        pd.setIndeterminate(false);
        pd.setCancelable(true);
        pd.show();


        //判断状态码
        BmobQuery<State> bmobQuery = new BmobQuery<State>();
        bmobQuery.getObject(InfoUtils.STATE_OBJ.toString(), new QueryListener<State>() {
            @Override
            public void done(State state, BmobException e) {
                if (e == null) {
//                    toast("查询成功");
                    //设置云端状态码
                    DBUtils.getInstance().setCloudState(state.getState());
                    //对比
                    calState(state.getState());

                } else {
                    toast("查询失败：" + e.getMessage());
//                    finish();
                }

            }
        });
        //状态码相同 进入

        //状态码不同 更新数据库

    }

    //对比状态码
    private void calState(final int state) {

        int localState = DBUtils.getInstance().getState();

        //如果本地状态码小于云端,那么将云端数据 根据状态码 储存到本地
        if (localState < state) {

            BmobQuery<Person> query = new BmobQuery<Person>();
            query.addWhereGreaterThanOrEqualTo("state", localState);
            query.findObjects(new FindListener<Person>() {
                @Override
                public void done(List<Person> list, BmobException e) {
                    if (e == null) {
                        toast("更新成功：共" + list.size() + "条数据。");
                        mNumSize = list.size();


                        if (list.size() == 0) {
                            registerHandle.sendEmptyMessage(0);
                        }

                        Log.i("bmob","保存数据");

                        for (int i = 0 ; i < list.size(); i++){
                            com.songlin.db.Person person = new com.songlin.db.Person();
                            Person gameScore = list.get(i);
                            BmobDate bmobDate = gameScore.getDate();

                            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                            format.parse(bmobDate.getDate());
                            person.setState(gameScore.getState());
                            person.setName(gameScore.getName());
                            person.setCardNum(gameScore.getCardNum());
                            person.setDate(bmobDate.getDate().toString());
                            person.setPhone(gameScore.getPhone());
                            person.setHeadName(String.valueOf(gameScore.getCardNum()));

                            mPersons.add(person);

                            ImageThread imageThread = new ImageThread(gameScore.getHeadUrl(), gameScore.getCardNum());
                            imageThread.start();
                        }
                        registerHandle.sendEmptyMessage(0);
                    } else {
                        Log.i("bmob","失败："+e.getMessage()+","+e.getErrorCode());
                    }
                }
            });


        } else {
            registerHandle.sendEmptyMessage(0);
        }

    }

    //异步线程
    class ImageThread extends Thread{
        private String url;
        private int cardNum;
        public ImageThread(String url, int cardNum){
            this.url = url;
            this.cardNum = cardNum;
        }
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Bitmap bitmap = BitmapUtils.getHttpBitmap(url);
            for (com.songlin.db.Person gameScore : mPersons) {
                if (gameScore.getCardNum() == cardNum) {

                    Log.i("bmob","本地数据" + gameScore.getCardNum());

                    BitmapUtils.saveImageToGallery(LoadingActivity.this, bitmap, String.valueOf(gameScore.getCardNum()));

                    DBUtils.getInstance().saveOnePerson(gameScore);
                    mNum++;

                    break;
                }
            }
//            if(mNum == mNumSize){
//                registerHandle.sendEmptyMessage(0);
//            }
        }
    }

    // 异步类，实现异步加载头像
    class ImageLoadTask extends AsyncTask<Object, Integer, Bitmap> {
        int cardNum;

        ProgressDialog pdialog;
        public ImageLoadTask(Context context){
            toast("异步任务");
            pdialog = new ProgressDialog(context, 0);
            pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int i) {
                    dialog.cancel();
                }
            });
            pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
            pdialog.setCancelable(true);
            pdialog.setMax(100);
            pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pdialog.show();
        }


        @Override
        protected Bitmap doInBackground(Object... params) {
            String url = (String) params[0];
            cardNum = (Integer) params[1];


            Bitmap bitmap = BitmapUtils.getHttpBitmap(url);


            for (com.songlin.db.Person gameScore : mPersons) {
                if (gameScore.getCardNum() == cardNum) {

                    Log.i("bmob","本地数据" + gameScore.getCardNum());

                    BitmapUtils.saveImageToGallery(LoadingActivity.this, bitmap, String.valueOf(gameScore.getCardNum()));

                    DBUtils.getInstance().saveOnePerson(gameScore);
                    mNum++;

                    break;
                }
            }

            if(mNum == mNumSize){
                registerHandle.sendEmptyMessage(0);
            }

            return bitmap;
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pdialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result == null) {
                return;
            }
            for (com.songlin.db.Person gameScore : mPersons) {
                if (gameScore.getCardNum() == cardNum) {

                    Log.i("bmob","本地数据" + gameScore.getCardNum());

                    BitmapUtils.saveImageToGallery(LoadingActivity.this, result, String.valueOf(gameScore.getCardNum()));

                    DBUtils.getInstance().saveOnePerson(gameScore);
                    mNum++;

                    mPersons.remove(gameScore);
                    break;
                }
            }

            if(mPersons.size() == 0){
                registerHandle.sendEmptyMessage(0);
            }
        }
    }

    // Handle用于接收服务器返回消息
    Handler registerHandle = new Handler() {

        public void handleMessage(Message msg) {

            if (pd != null && pd.isShowing()) {
                pd.dismiss();
            }
            switch (msg.what) {
                case 0:
                    // 跳转

                    Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 1:
                    // 跳转

                    break;
                default:
                    break;
            }
        };
    };


    //测试输出
    private void toast(String str) {
        Toast.makeText(LoadingActivity.this, str, Toast.LENGTH_SHORT).show();
    }
}
